<template>
  <div>
    <Category :scene="scene" />

    <el-card style="margin: 10px 0" v-loading="loading">
      <div v-show="scene == 0">
        <el-button :disabled="!categoryStore.c3Id" type="primary" size="default" icon="Plus" @click="addSpu">添加SPU</el-button>

        <el-table border style="margin: 10px 0" :data="records">
          <el-table-column label="序号" width="80px" align="center" type="index" />
          <el-table-column label="SPU名称" prop="spuName" />
          <el-table-column label="SPU描述" prop="description" show-overflow-tooltip />
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button type="primary" size="small" icon="Plus" @click="addSku(row)" title="新增" />
              <el-button type="warning" size="small" icon="Edit" @click="updateSpu(row)" title="修改" />
              <el-button type="info" size="small" icon="View" @click="findSku(row)" title="查看" />
              <el-popconfirm :title="`是否确定删除该已有的${row.spuName}`" width="200px" @confirm="deleteSpu(row)">
                <template #reference>
                  <el-button type="danger" size="small" icon="Delete" title="删除" />
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          v-model:currentPage="pageNo"
          v-model:page-size="limit"
          :page-sizes="[3, 5, 7, 9]"
          layout="prev, pager, next, jumper, ->,sizes, total"
          @current-change="getHasSpu"
          @size-change="sizeChange"
          :total="total"
          background
        />
      </div>

      <!-- 添加，修改spu -->
      <!-- 获取数据不能在子组件中onMounted发送，因为v-show在父组件中是直接加载的，子组件还没切换就已经发送请求了 -->
      <spuForm ref="spuFormRef" v-show="scene == 1" @changeScene="changeScene" />
      <!-- 添加sku -->
      <skuForm ref="skuFormRef" v-show="scene == 2" @changeScene="changeScene" />
      <!-- 查看具体sku -->
      <skuInfo ref="skuInfoRef" />
    </el-card>
  </div>
</template>

<script setup lang="ts">
  import { nextTick, onBeforeUnmount, ref, watch } from 'vue'
  import { reqHasSpu, reqRemoveSpu } from '@/api/product/spu/index'
  import type { HasResponseData, Records, SpuData } from '@/api/product/spu/type'
  import useCategoryStore from '@/store/modules/category'
  import { getElMessage } from '@/utils/message'
  import skuForm from './skuForm.vue'
  import spuForm from './spuForm.vue'
  import skuInfo from './skuInfo.vue'

  const categoryStore = useCategoryStore()
  const scene = ref<number>(0) // 0: 显示已有的SPU 1: 添加或修改已有的SPU 2：添加SKU的结构
  const pageNo = ref<number>(1)
  const limit = ref<number>(3)
  const total = ref<number>(0)
  const loading = ref<boolean>(false)
  const records = ref<Records>([])
  const spuFormRef = ref<any>()
  const skuInfoRef = ref<InstanceType<typeof skuInfo>>()
  watch(
    () => categoryStore.c3Id,
    () => {
      records.value = []
      if (!categoryStore.c3Id) return
      getHasSpu()
    },
  )

  // 获取原始列表数据
  async function getHasSpu(pager = 1) {
    try {
      // 不穿pager默认捞取第一页数据
      pageNo.value = pager
      loading.value = true
      const res: HasResponseData = await reqHasSpu(pageNo.value, limit.value, categoryStore.c3Id)
      if (res.code === 200) {
        records.value = res.data.records
        total.value = res.data.total
      } else {
        getElMessage('获取SPU列表数据失败', 'error')
      }
    } catch (error) {
      getElMessage((error as Error).message, 'error')
    } finally {
      loading.value = false
    }
  }

  // 大切换pu
  function addSpu() {
    scene.value = 1
    spuFormRef.value.initalHasSpuData(categoryStore.c3Id)
  }

  // 切换spuForm
  function updateSpu(row: SpuData) {
    scene.value = 1
    spuFormRef.value.initalHasSpuData(row)
  }

  // 切换skuInfo
  function findSku(row: SpuData) {
    skuInfoRef.value?.openSkuDialog(row)
  }

  // 切换sku
  const skuFormRef = ref<InstanceType<typeof skuForm>>()
  function addSku(row: SpuData) {
    scene.value = 2
    nextTick(() => {
      skuFormRef.value?.initSkuData(categoryStore.c1Id, categoryStore.c2Id, row)
    })
  }

  // 删除
  async function deleteSpu(row: SpuData) {
    try {
      const res = await reqRemoveSpu(row.id as number)
      if (res.code === 200) {
        getElMessage(`删除${row.spuName}成功`, 'success')
        getHasSpu(records.value.length > 1 ? pageNo.value : pageNo.value - 1)
      } else {
        getElMessage(`删除${row.spuName}失败`, 'error')
      }
    } catch (error) {
      getElMessage((error as Error).message, 'error')
    }
  }

  // 自定义事件
  function changeScene(obj: any) {
    scene.value = obj.flag
    // 编辑需要保存当前编辑页
    getHasSpu(obj.isEidt ? pageNo.value : 1)
  }

  // 分页
  const sizeChange = () => {
    // limit使用的v-model双向绑定，因此在修改的时候已经记录limit，此时不需要在函数中设置一边
    getHasSpu()
  }

  onBeforeUnmount(() => {
    categoryStore.$reset()
  })
</script>

<style lang="scss" scoped></style>
